package com.zhijian.medical.controller;

import java.util.*;

import com.zhijian.medical.dao.local.RoutinePatientMapper;
import com.zhijian.medical.entity.po.*;
import com.zhijian.medical.entity.vo.request.*;
import com.zhijian.medical.entity.vo.response.*;
import com.zhijian.medical.enums.RoutineHistoryEnum;
import com.zhijian.medical.enums.RoutinePathologySampleStepEnum;
import com.zhijian.medical.enums.RoutineRsEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.zhijian.response.annotation.Response;
import com.zhijian.util.page.Page;

import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 常规病理-染色 控制层
 * 
 * @author auto
 * @version 1.0
 * @date 2024-07-26 16:47:47
 */
@Slf4j
@Controller
@Api(tags = "常规病理-染色")
public class RoutinePathologyRsController {

	@Autowired
    private RoutinePathologyRsService service;

	@Autowired
	private RoutinePatientMapper routinePatientMapper;

    @Autowired
    private RoutineSingleSampleService singleSampleService;

    @Autowired
    private RoutineQcService qcService;

    @Autowired
    private RoutineHistoryService historyService;

    @Autowired
    private RoutineStepService stepService;

    @Autowired
    private RoutineStepRecordService stepRecordService;

    @Autowired
    private RoutineSingleSampleQpService routineSingleSampleQpService;
    @Autowired
    private SpecialInstructionService specialInstructionService;
    @Autowired
    private RoutinePatientYzService routinePatientYzService;

    /**
     * 输入框输入数据
     *
     * @param numbers
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/rs/{numbers}")
    @ApiOperation("染色-输入脱水框")
    public boolean inputNums(@PathVariable("numbers")String numbers) {
        log.info("{} - {}| query info", this.getClass().getSimpleName(), numbers);
        return service.inputNums(numbers);
    }

    /**
     * 染色-染色列表
     *
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/rs/list")
    @ApiOperation("染色-染色列表")
    public List<RoutinePathologyRsRsVo> selectList() {
        log.info("{} -| query info", this.getClass().getSimpleName());
        List<RoutinePathologyRsVo> routinePathologyRsVos = service.selectList(RoutinePathologyRsSearchVo.builder().build());
        List<RoutinePathologyRsRsVo> resultList = new ArrayList<>();
        for (RoutinePathologyRsVo vo : routinePathologyRsVos) {
            RoutinePathologyRsRsVo rsRsVo = new RoutinePathologyRsRsVo();
            BeanUtils.copyProperties(vo, rsRsVo);
            if (!vo.getStep().equals(RoutineRsEnum.OVER.getCode().byteValue())) {
                resultList.add(rsRsVo);
            }
        }
        return resultList;
    }

    @Response
    @GetMapping("/routine/pathology/rs/flow")
    @ApiOperation("染色-染色流程信息")
    public RoutinePathologyRsInfoRsVo selectFlowList() {
        log.info("{} -| query info", this.getClass().getSimpleName());
        RoutinePathologyRsInfoRsVo rsInfoRsVo = new RoutinePathologyRsInfoRsVo();
        // 查询所有样本
        List<RoutinePathologyRsVo> routinePathologyRsVos = service.selectList(RoutinePathologyRsSearchVo.builder().build());
        List<RoutinePathologyRsRsVo> resultList = new ArrayList<>();
        int i = 1;
        for (RoutinePathologyRsVo vo : routinePathologyRsVos) {
            RoutinePathologyRsRsVo rsRsVo = new RoutinePathologyRsRsVo();
            BeanUtils.copyProperties(vo, rsRsVo);
            if (!vo.getStep().equals(RoutineRsEnum.OVER.getCode().byteValue())) {
                rsRsVo.setSort(String.valueOf(i++));
                resultList.add(rsRsVo);
            }
        }
        rsInfoRsVo.setRsInfoVos(resultList);
        // 获取所有流程
        Map<String, String> flowMaps = RoutineRsEnum.getMap();
        Map<String, RoutinePathologyRsInfoRsVo.InfoRsVo> flowInfo = new HashMap<>();
        // 遍历字典
        for (Map.Entry<String, String> entry : flowMaps.entrySet()) {
            RoutinePathologyRsInfoRsVo.InfoRsVo infoRsVo = new RoutinePathologyRsInfoRsVo.InfoRsVo();
            infoRsVo.setFlowName(entry.getValue());
            List<RoutinePathologyRsRsVo> collect = resultList.stream().filter(routinePathologyRsVo -> routinePathologyRsVo.getStep().equals(Byte.valueOf(entry.getKey())))
                    .collect(Collectors.toList());
            infoRsVo.setSample(collect);

            flowInfo.put(entry.getKey(), infoRsVo);
        }
        rsInfoRsVo.setFlowInfo(flowInfo);
        return rsInfoRsVo;
    }

    /**
     * 获取染色详情
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/rs/info/{numbers}")
    @ApiOperation("获取染色详情")
    public RoutinePathologyRsVo pathologyInfo(@PathVariable("numbers")String numbers) {
        log.info("{} | query info", this.getClass().getSimpleName());
        return service.pathologyInfo(numbers);
    }

    /**
     * 样本详情
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/rs/sample")
    @ApiOperation("样本详情")
    public List<RoutineSingleSampleRsVo> pathologySampleRsInfo() {
        return service.pathologySampleRsInfo();
    }

    /**
     * 样本详情
     * @return
     */
    @Response
    @PostMapping("/routine/pathology/sp/sample")
    @ApiOperation("送片-切片列表")
    public List<RoutineSingleSampleQp> pathologySampleRsInfo(@RequestBody List<String>  rsjCodeList) {
        //List<RoutineSingleSampleVo> voList = new ArrayList<>();
        List<RoutineSingleSampleQp> voList = routineSingleSampleQpService.selectListByRsjCode(rsjCodeList);
        if (!CollectionUtils.isEmpty(voList)){
            List<Long> sampleIdList = voList.stream().map(RoutineSingleSampleQp::getSampleId).distinct().collect(Collectors.toList());
            List<RoutineSingleSampleVo> routineSingleSampleList = singleSampleService.selectList(RoutineSingleSampleSearchVo.builder().idList(sampleIdList).build());
            for (RoutineSingleSampleVo routineSingleSampleVo : routineSingleSampleList){
                String bingLiHao = qcService.selectById(routineSingleSampleVo.getQcId()).getConventionPathologyNumber();
//                Integer count = historyService.count(RoutineHistorySearchVo.builder()
//                                .step(RoutineHistoryEnum.SP.getCode().byteValue())
//                        .number(routineSingleSampleVo.getNumber()).build());
//                com.zhijian.medical.util.AssertUtil.check(count > 0, "信息已录入");
                // 增加送片记录
                historyService.insert(RoutineHistory.builder()
                        .conventionPathologyNumber(bingLiHao)
                        .step(RoutineHistoryEnum.SP.getCode().byteValue())
                        .number(routineSingleSampleVo.getNumber())
                        .build());
                // 增加病理号流程记录
                String contetnt = "送片";
                RoutineStepVo routineStepVo = stepService.selectOne(RoutineStepSearchVo.builder().conventionPathologyNumber(bingLiHao).build());
                if (routineStepVo.getStep() < RoutinePathologySampleStepEnum.SP.getCode().byteValue()) {
                    stepService.updateStepByNums(bingLiHao, contetnt, RoutinePathologySampleStepEnum.SP.getCode().byteValue());
                    stepRecordService.insert(RoutineStepRecord.builder()
                            .conventionPathologyNumber(bingLiHao)
                            .step(RoutinePathologySampleStepEnum.SP.getCode().byteValue())
                            .content(contetnt)
                            .build());
                }
                //修改病人的步骤状态
                routinePatientMapper.updateByPrimaryKeySelectiveBlh(RoutinePatient.builder()
                        .step(RoutinePathologySampleStepEnum.SP.getCode().byteValue())
                        .conventionPathologyNumber(bingLiHao).build());
                // 修改特殊医嘱的状态
                String number = routineSingleSampleVo.getNumber();
                List<SpecialInstructionVo> specialInstructionVos = specialInstructionService.selectList(SpecialInstructionSearchVo.builder().waxBlock(number).build());
                for (SpecialInstructionVo specialInstructionVo : specialInstructionVos) {
                    specialInstructionService.updateByPrimaryKeySelective(SpecialInstruction.builder().id(specialInstructionVo.getId()).status((byte)1).build());
                }
                // 修改医嘱状态
                routinePatientYzService.updateByLkh(routineSingleSampleVo.getId());
            }
//        for (String rsjCode : rsjCodeList) {
//            RoutineSingleSampleVo routineSingleSampleVo = singleSampleService.selectOne(RoutineSingleSampleSearchVo.builder().rsjCode(rsjCode).build());
//            //voList.add(routineSingleSampleVo);
//
//            String bingLiHao = qcService.selectById(routineSingleSampleVo.getQcId()).getConventionPathologyNumber();
//
//            Integer count = historyService.count(RoutineHistorySearchVo.builder()
//                            .step(RoutineHistoryEnum.SP.getCode().byteValue())
//                    .number(routineSingleSampleVo.getNumber()).build());
//            com.zhijian.medical.util.AssertUtil.check(count > 0, "信息已录入");
//            // 增加送片记录
//            historyService.insert(RoutineHistory.builder()
//                    .conventionPathologyNumber(bingLiHao)
//                    .step(RoutineHistoryEnum.SP.getCode().byteValue())
//                    .number(routineSingleSampleVo.getNumber())
//                    .build());
//            // 增加病理号流程记录
//            String contetnt = "送片";
//            RoutineStepVo routineStepVo = stepService.selectOne(RoutineStepSearchVo.builder().conventionPathologyNumber(bingLiHao).build());
//            if (routineStepVo.getStep() < RoutinePathologySampleStepEnum.SP.getCode().byteValue()) {
//                stepService.updateStepByNums(bingLiHao, contetnt, RoutinePathologySampleStepEnum.SP.getCode().byteValue());
//                stepRecordService.insert(RoutineStepRecord.builder()
//                        .conventionPathologyNumber(bingLiHao)
//                        .step(RoutinePathologySampleStepEnum.SP.getCode().byteValue())
//                        .content(contetnt)
//                        .build());
//            }
        }
        return voList;
    }

    /**
     * 样本详情
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/sp/rysj/{qcId}")
    @ApiOperation("送片-肉眼所见")
    public String spRysj(@ApiParam(name = "qcId", value = "取材id")  @PathVariable("qcId")Long qcId) {
        RoutineQcVo qc = qcService.selectVoById(qcId);
        return qc.getRySj();
    }
}